//用户相关小仓库
import { defineStore } from 'pinia'
//引入接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from '@/api/user/type'
import type { UserState } from './types/type'
//引入操作本地存储
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '../../utils/token'

//引入路由：常量路由
import { constantRoute } from '../../router/routes'

//创建用户小仓库
const useUserStore = defineStore('User', {
  //小仓库存储数据地方
  state: (): UserState => {
    return {
      //存储用户唯一标识token
      //从本地存储获取，保证刷新后还有TOKEN
      // token: localStorage.getItem('TOKEN'),
      token: GET_TOKEN(),
      menuRoutes: constantRoute, //存储生成菜单需要的数组路由
      username: '',
      avatar: '',
    }
  },
  //异步逻辑的地方
  actions: {
    //用户登录的方法
    async userLogin(data: loginFormData) {
      // console.log("data:",data);
      //登录请求
      const result: loginResponseData = await reqLogin(data)
      console.log('result', result)
      //登录成功：200->token
      //登录失败：201->失败信息
      if (result.code == 200) {
        //pinia存储token
        this.token = result.data as string
        //本地持久化
        // localStorage.setItem('TOKEN', (result.data.token as string))
        SET_TOKEN(result.data as string)
        return 'ok'
      } else {
        // console.log(1234)
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息
    async userInfo() {
      // console.log(1234)
      //获取用户信息存储仓库中：用户头像，名字
      const result: userInfoResponseData = await reqUserInfo()
      console.log(result)
      //如果获取用户信息成功，就存储信息
      if (result.code == 200) {
        this.username = result.data.username
        this.avatar = result.data.avatar
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //退出登录
    async userLogout() {
      const result = await reqLogout()
      if (result.code == 200) {
        console.log(result)
        //没有mock接口：退出登录接口
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  //计算属性
  getters: {},
})
//对外暴露小仓库
export default useUserStore
